package com.cetsk.android.talkorigins;

import java.io.IOException;
import java.net.URL;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import android.content.Context;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;

public class HTMLParse  {
	Context appContext = null;
	DatabaseHelper dbh = null;
	HTMLParse(Context context){
		appContext = context;
		dbh = new DatabaseHelper(appContext);
		if(getClaimCount() != 637){
			dbh.getWritableDatabase().execSQL("DELETE FROM " + DatabaseHelper.CLAIMS_TABLE + "; VACUUM");
			addClaims();
		}
		dbh.close();
	}
	
	public int getClaimCount(){
		SQLiteStatement stmt = dbh.getWritableDatabase().compileStatement("select count(*) from " + DatabaseHelper.CLAIMS_TABLE);
	    return (int) stmt.simpleQueryForLong();
	}

	public String getHtml(String url){
		Document doc;
		try {
			URL urlRef = new URL(url);
			doc = Jsoup.parse(urlRef, 10000);
			String html = doc.toString();
			int startPos = html.indexOf("<h2 class=\"c\">");
			int endPos = html.indexOf("<hr size=\"0\" />", startPos);
			if(startPos > 0 && endPos > 0){
				html = html.substring(startPos, endPos);
			}
			return html;
		} catch(Exception e){
			e.printStackTrace();
			//Log.e("ERROR",e.getMessage());
		}
		return null;
	}
	
	public int getLastInsertedClaimId(){
		SQLiteStatement stmt = dbh.getWritableDatabase().compileStatement("SELECT Id FROM "+DatabaseHelper.CLAIMS_TABLE+" ORDER BY Id DESC LIMIT 1");
	    return (int) stmt.simpleQueryForLong();
	}
	
	public void addClaims(){
		Document doc;
		try {
			doc = Jsoup.connect("http://www.talkorigins.org/indexcc/list.html").get();
			Elements cats = doc.getElementsByTag("h2");

			dbh.getWritableDatabase().beginTransaction();
			for( Element e : cats){
				Elements anchors = e.getElementsByTag("a");
				Element anchor = anchors.get(0);
				Elements subClaims = e.nextElementSibling().children();

				SQLiteStatement stmt = dbh.getWritableDatabase().compileStatement("INSERT INTO " + DatabaseHelper.CLAIMS_TABLE + " (Id,ParentId,Key,Name,Url,Content) VALUES (null,?,?,?,?,?)");
				int parentId = 0;
				
				stmt.bindLong(1, parentId);
				stmt.bindString(2, anchor.attr("name"));
				stmt.bindString(3, e.text());
				stmt.bindString(4, "");
				stmt.execute();
				
				recurseClaims(subClaims,getLastInsertedClaimId());
			}
			dbh.getWritableDatabase().setTransactionSuccessful();
			dbh.getWritableDatabase().endTransaction();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} catch (Exception e){
			Log.e("ERROR",e.getMessage());
		} finally {
		}
	}
	public void recurseClaims(Elements elements, int parentId) {
		SQLiteStatement stmt = dbh.getWritableDatabase().compileStatement("INSERT INTO " + DatabaseHelper.CLAIMS_TABLE + " (Id,ParentId,Key,Name,Url,Content) VALUES (null,?,?,?,?,?)");
		for( Element e : elements){
			Elements anchors = e.getElementsByTag("a");
			if(anchors.size() > 0){
				Element anchor = anchors.get(0);

				stmt.bindLong(1, parentId);
				stmt.bindString(2, anchor.attr("name"));
				if(anchor.attr("href").equals("")){
					stmt.bindString(3, anchor.text() + "" + e.ownText());
				} else {
					stmt.bindString(3, e.ownText() + "" + anchor.text());
				}
				stmt.bindString(4, anchor.attr("href"));
				stmt.execute();
				
				Elements ch = e.getElementsByTag("ul");
				if(ch.size() > 0){
					recurseClaims(ch.get(0).children(),getLastInsertedClaimId());
				}
			} else {
				continue;
			}
		}
	}
}
